import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Radio,
  Tooltip,
  Divider, message, Modal, Icon,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import CheckCompany from './check';
import DrawerComponent from './drawerInfo';
import styles from '../UserManage.less';
import router from 'umi/router';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ companyModels, loading }) => ({
  companyModels,
  loading: loading.models.companyModels,
}))

@Form.create()
class CompanyManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      visibleDrawer: false,
      updateModalVisible: false,
      selectedRows: {},
      formValues: {},
      status: 2,
      visibleCheck: false,
    };
  }


  status = (record) => {
    let arr = ['草稿', '待审核', '已通过', <div key={'tip'}><Tooltip title={record.reason}>已驳回<Icon
      style={{ color: 'rgba(0, 0, 0, 0.43)', marginLeft: 4 }}
      type="info-circle-o"
    /></Tooltip></div>, 1, '已开户'];
    return arr[record.status - 1];
  };




  lookDom(record) {
    let dom = powerBtnFunc('100034', <a key={'view'} onClick={() => this.visibleDrawerInfo(true, record)}>查看</a>);
    return dom;
  }

  checkDom(record, disabled) {
    let dom = powerBtnFunc('100037', <a key={'check'} disabled={disabled} onClick={() => this.handleCheck(true, record)}>审核</a>);
    return dom;

  }

  editDom(record) {
    let dom = powerBtnFunc('100033', <a key={'eidt'} onClick={() => this.handleUpdateModalVisible(record)}>编辑</a>);
    return dom;
  }

  delDom(record) {
    let dom = powerBtnFunc('100038', <a key={'del'} onClick={() => this.handleMenuClick(record)}>删除</a>);
    return dom;
  }

  operation3 = (text, record) => [
    (<Fragment key={'Fragment'}>

      {this.lookDom(record)}
        <Divider key={'divider'} type="vertical"/>
        {this.checkDom(record, true)}
      </Fragment>
    ),
  ];
  operation2 = (text, record) => [
    (<Fragment key={'Fragment'}>

      {this.editDom(record)}
        <Divider key={'divider'} type="vertical"/>
        {this.lookDom(record)}
        <Divider key={'divider1'} type="vertical"/>
        {this.checkDom(record, false)}
      </Fragment>
    ),
  ];
  operation1 = (text, record) => [
    (<Fragment key={'Fragment'}>

      {this.editDom(record)}
        <Divider key={'divider'} type="vertical"/>
        {this.lookDom(record)}
        <Divider key={'divider1'} type="vertical"/>
        {this.checkDom(record, false)}
      </Fragment>
    ),
  ];
  operation6 = (text, record) => [
    (<Fragment key={'Fragment'}>

      {this.lookDom(record)}
      </Fragment>
    ),
  ];
  operation4 = (text, record) => [
    (<Fragment key={'Fragment'}>

        {this.editDom(record)}
        <Divider key={'divider'} type="vertical"/>
        {this.lookDom(record)}
        <Divider key={'divider1'} type="vertical"/>
        {this.delDom(record)}
      </Fragment>
    ),
  ];

  componentDidMount() {
    const { dispatch } = this.props;

    const { query: { status } } = this.props.location;
    // 请求用户列表
    this.setState({
      status: Number(status) || 2,
    }, () => {
      dispatch({
        type: 'companyModels/fetch',
        payload: {
          status: status || 2,
        },
      });
    });
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    dispatch({
      type: 'companyModels/fetch',
      payload: params,
    });
  };
  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { query } = this.props.location;

    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'companyModels/fetch',
      payload: query,
    });
  };


  handleMenuClick = (row) => {
    const { dispatch } = this.props;
    const { status } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该企业吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'companyModels/remove',
          payload: {
            code: row.enterpriseNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              dispatch({
                type: 'companyModels/fetch',
                payload: {
                  status: status,
                },
              });
            } else {
              message.error(res.msg);
            }
          },
        });
      },
    });

  };

  // 搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;
    const { status } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        status: status,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'companyModels/fetch',
        payload: values,
      });
    });
  };
  // 新建
  handleModalVisible = flag => {
    const { status } = this.state;
    localStorage.removeItem('step1');
    localStorage.removeItem('step2');
    localStorage.removeItem('step3');
    localStorage.removeItem('enterpriseDetail');
    router.push({
      pathname: '/preloan/enterprise/create/step1', query: {
        status: status,
      },
    });
  };
  // 修改
  handleUpdateModalVisible = (record) => {
    const { status } = this.state;

    localStorage.removeItem('step1');
    localStorage.removeItem('step2');
    localStorage.removeItem('step3');
    localStorage.removeItem('enterpriseDetail');
    const { dispatch } = this.props;
    dispatch({
      type: 'companyModels/getEnterpriseDesc',
      payload: {
        code: record.enterpriseNo,
      },
      callback() {
        router.push({
          pathname: '/preloan/enterprise/create/step1',
          query: {
            status: status,
          },
        });
      },
    });


  };
  // 审核
  handleCheck = (flag, record) => {
    this.setState({
      visibleCheck: !!flag,
      selectedRows: record,
    });
  };

  passCheck = (flag, record) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let _this = this;
    dispatch({
      type: 'companyModels/audit',
      payload: { code: selectedRows.enterpriseNo, ...record },
      callback(res) {
        if (res.code === 200) {
          _this.handleCheck(false, []);
          dispatch({
            type: 'companyModels/fetch',
            payload: {
              status: _this.state.status,
            },
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }

      },
    });
  };

  // 新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'companyModels/add',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'companyModels/fetch',
        });
      },
    });

    // this.handleModalVisible();
  };
  //修改请求
  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'companyModels/update',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'companyModels/fetch',
        });
      },
    });

  };
  //状态
  onChange = (e) => {
    const { dispatch } = this.props;
    router.push({
      pathname: '/preloan/enterprise',
      query: {
        status: e.target.value,
      },
    });
    this.setState({ status: e.target.value });
    dispatch({
      type: 'companyModels/fetch',
      payload: {
        status: e.target.value,
      },

    });
  };


  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="企业编码">
              {getFieldDecorator('enterpriseNo')(<Input placeholder="请输入企业编码"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入企业名称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="企业简称">
              {getFieldDecorator('shortName')(<Input placeholder="请输入企业简称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>


      </Form>
    );
  }

  visibleDrawerInfo = (flag, recod) => {
    const { dispatch } = this.props;
    let _this = this;
    if (flag) {
      dispatch({
        type: 'companyModels/getEnterpriseDesc',
        payload: { code: recod.enterpriseNo },
        callback() {
          _this.setState({
            visibleDrawer: true,
          });
        },
      });
    } else {
      this.setState({
        visibleDrawer: false,
      });
    }
  };

  render() {
    const { companyModels: { data, companyDesc = {} }, loading } = this.props;
    const { selectedRows, status, visibleCheck, visibleDrawer } = this.state;

    const columns = [
      {
        title: '企业编码',
        dataIndex: 'enterpriseNo',
        key: 'enterpriseNo',

      },
      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
        key: 'enterpriseName',
      },
      {
        title: '企业简称',
        dataIndex: 'shortName',
        key: 'shortName',
      },

      {
        title: '法人代表',
        dataIndex: 'legalName',
        key: 'legalName',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '创建人',
        dataIndex: 'createName',
        key: 'createName',
      },
      {
        title: '状态',
        key: 'status',
        render: ((text) => {
          return <span>{this.status(text)}</span>;
        }),
      },
      {
        title: '操作',
        render: (text, record) => {
          if (status === 4) {
            return this.operation4(text, record);
          } else if (status === 3) {
            return this.operation3(text, record);
          } else if (status === 2) {
            return this.operation2(text, record);
          } else if (status === 1) {
            return this.operation1(text, record);
          } else if (status === 6) {
            return this.operation6(text, record);
          }
        },

      },
    ];
    return (
      <PageHeaderWrapper title="企业管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100032',
                  <Button icon="plus" key={'create'} type="primary" onClick={() => this.handleModalVisible()}>
                    添加企业
                  </Button>,
                )
              }

              <Radio.Group value={status} onChange={this.onChange} style={{ marginBottom: 16 }}>
                <Radio.Button value={2} key={'2'}>待审核</Radio.Button>
                <Radio.Button value={3} key={'3'}>通过</Radio.Button>
                <Radio.Button value={4} key={'4'}>驳回</Radio.Button>
                {/*<Radio.Button value={6} key={6}>开户</Radio.Button>*/}
              </Radio.Group>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowSelectHide={true}
              rowKey={'enterpriseNo'}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DrawerComponent
          visible={visibleDrawer}
          descInfo={companyDesc ? companyDesc : {}}
          onClose={this.visibleDrawerInfo}/>
        <CheckCompany
          visibleCheck={visibleCheck}
          passCheck={this.passCheck}
          handleCheck={this.handleCheck}/>
      </PageHeaderWrapper>
    );
  }
}

export default CompanyManage;
